package com.zzy;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Comsumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.下面的这个就是建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("101.42.52.162");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("zzy12month");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("mq");
        Connection connection = connectionFactory.newConnection();

        //2.下面的这个就是开放信道
        Channel channel = connection.createChannel();

        //3.声明队列（这个是可以省略的）
        //channel.queueDeclare("hello", true, false, false, null);

        //4.消费消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            //从队列里面收到消息就会执行这个方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息"+new String(body));
            }
        };
        channel.basicConsume("hello", true, consumer );
//        System.out.println("接收到消息");
        Thread.sleep(2000);
        //5.释放资源
        channel.close();
        connection.close();
    }
}
